#include <Arduino.h>
#include <SD.h>
#include <FS.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <axp20x.h>
#define SDIO_CLK 6
#define SDIO_CMD 7
#define SDIO_D0 5
#define SDIO_D1 -1
#define SDIO_D2 -1
#define SDIO_D3 15
#define SD_SENSOR 4

#define I2C_SDA 14
#define I2C_SCL 21
#define AXP192_IRQ 13
#define RTC_IRQ 12

#define TOUCH_RST 46
#define LCD_DC 45
#define LCD_WR 48
#define LCD_RD 47
#define LCD_D0 0
#define LCD_D1 38
#define LCD_D2 39
#define LCD_D3 40
#define LCD_D4 41
#define LCD_D5 42
#define LCD_D6 2
#define LCD_D7 1
////////////////////////模块IO配置（可复用）/////////////////////////

#define I2C1_SDA 10
#define I2C1_SCL 11

#define I2S_LRCLK 16
#define I2S_BCLK 17
#define I2S_DATA 8

#define IR_LED 10

#define SD_MISO SDIO_D0
#define SD_MOSI SDIO_CMD
#define SD_SCLK SDIO_CLK
#define SD_CS SDIO_D3
AXP20X_Class axp;
#define screenWidth 320
#define screenHeight 240
int frameid = 0;
SPIClass SDSPI = SPIClass(FSPI);
void initHardware(bool wifi = false)
{
    Serial.begin(115200);
    pinMode(SD_CS, OUTPUT);
    digitalWrite(SD_CS, HIGH);
    SDSPI.begin(SD_SCLK, SD_MISO, SD_MOSI, -1);
    SD.begin(SD_CS, SDSPI, 40000000);
    Wire.begin(I2C_SDA, I2C_SCL);
    int ret = axp.begin(Wire, AXP192_SLAVE_ADDRESS);
    if (ret == AXP_FAIL)
    {
        Serial.println("AXP Power begin failed");
        while (1)
            ;
    }

    axp.setVWarningLevel1(3450);
    axp.setVWarningLevel2(3400);
    axp.setPowerDownVoltage(3300);

    //! enable all irq channel
    axp.enableIRQ(AXP202_PEK_SHORTPRESS_IRQ, true);
    axp.clearIRQ();

    axp.setPowerOutPut(AXP192_LDO2, AXP202_OFF);
    axp.setPowerOutPut(AXP192_LDO3, AXP202_OFF);
    axp.setPowerOutPut(AXP192_DCDC2, AXP202_OFF);
    axp.setPowerOutPut(AXP192_DCDC1, AXP202_OFF);

    axp.setShutdownTime(AXP_POWER_OFF_TIME_4S);
    axp.setlongPressTime(AXP_LONGPRESS_TIME_2S);
    axp.setStartupTime(AXP192_STARTUP_TIME_128MS);
    axp.adc1Enable(AXP202_BATT_VOL_ADC1 | AXP202_BATT_CUR_ADC1 | AXP202_ACIN_CUR_ADC1 | AXP202_ACIN_VOL_ADC1 | AXP202_VBUS_CUR_ADC1 | AXP202_VBUS_VOL_ADC1, true);

    axp.setChargingTargetVoltage(AXP202_TARGET_VOL_4_2V);
    axp.setAdcSamplingRate(AXP_ADC_SAMPLING_RATE_100HZ);
    axp.setTSmode(AXP_TS_PIN_MODE_DISABLE);
    pinMode(AXP192_IRQ, INPUT_PULLUP);
    pinMode(SD_SENSOR, INPUT_PULLUP);

    axp.setPowerOutPut(AXP192_DCDC1, AXP202_ON);
    axp.setDCDC1Voltage(2480 + (uint16_t)60 * 5);

    Serial.println("开始连接WiFi");
    WiFi.begin("lxy", "zah1971896611lxy");
    while (WiFi.isConnected() == false)
        delay(200);
}